<?php
declare (strict_types = 1);

namespace ui;

/**
 * 
 */
class Table
{
    private $columns = [];
    private $buttons = [];
    private $searchs = [];
    private $exports = [];

    private $url = '';

    public static function create() {
        $builder = new Table();
        return $builder;
    }

    public function withQueryUrl($url) {
        $this->url = $url;
        return $this;
    }

    public function addSelection($width = 40) {
        $this->addColumn(TableColumn::createSelection($width)->setWidth($width));
        return $this;
    }

    public function addColumn(TableColumn $column) {
        $this->columns[] = $column;
        return $this;
    }

    public function addButton(Button $button) {
        $this->buttons[] = $button;
        return $this;
    }

    public function addSearch(FormField $field) {
        $this->searchs[] = $field;
        return $this;
    }

    public function addExportExcel() {
        $this->exports[] = 'excel';
        return $this;
    }

    public function build() {
        $buttons = [];
        foreach ($this->buttons as $btn) {
            $buttons[] = $btn->build();
        }
        $columns = [];
        foreach ($this->columns as $col) {
            $columns[] = $col->build();
        }
        $searchs = [];
        foreach ($this->searchs as $field) {
            $searchs[] = $field->build();
        }
        return [
            'searchs' => $searchs,
            'buttons' => $buttons,
            'columns' => $columns,
            'exports' => $this->exports,
            'url' => $this->url,
            'query' => $_GET,
        ];
    }

    public function buildJson() {
        return json_encode($this->build());
    }
}
